package com.example.myhotel.Inerceptor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.myhotel.common.BaseContext;
import com.example.myhotel.entity.Customers;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //放行OPTIONS请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        /*//2.拿到请求头里面的token（如果是第一次登录，那么是没有请求头的）
        String u_token = request.getHeader("u-token");
        if (u_token != null) {
            String uToken = stringRedisTemplate.opsForValue().get("uToken");
            String userId = stringRedisTemplate.opsForValue().get("userId");
            if (uToken != null && userId != null){
                stringRedisTemplate.opsForValue().set("uToken",u_token,30,TimeUnit.MINUTES);
                stringRedisTemplate.opsForValue().set("userId",userId,30,TimeUnit.MINUTES);
                return true;
            }

        }*/
        String utoken = request.getHeader("u-token");
        log.error(utoken);
        if (utoken !=null){
            String userJSON = stringRedisTemplate.opsForValue().get("TOKEN_" + utoken);
            log.error(userJSON);

            Customers user = JSON.parseObject(userJSON,Customers.class);

            BaseContext.setCurrentId(user.getId());
            log.error(BaseContext.getCurrentId());

            long id = Thread.currentThread().getId();
            log.error("线程id为：{}",id);

            if(!StringUtils.isBlank(userJSON)){
                stringRedisTemplate.opsForValue().set("TOKEN_"+utoken,JSON.toJSONString(user),1,TimeUnit.DAYS);
                return true;
            }

        }



        String a_token = request.getHeader("a-token");
        if (a_token != null){
            String aToken = stringRedisTemplate.opsForValue().get("aToken");
            if (aToken != null){
                stringRedisTemplate.opsForValue().set("aToken",a_token,30,TimeUnit.MINUTES);
                return true;
            }
        }


        response.setContentType("application/json; charset=utf-8");

        response.getWriter().print("{\"success\":false,\"msg\":\"NoUser\"}");

        return false;

    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}

